﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OracleClient;
using DB;
using System.Data;

namespace IBS
{
    public partial class IbsDataContext
    {

        /// <summary>
        /// Сохранение поставки в базу IBS
        /// </summary>
        /// <param name="delivery"></param>
        public Int64 SavePurchasePrice(EDEX_PURCHASE_PRICE PurchasePrice)
        {
            var headerId = SavePurchasePriceHeader(PurchasePrice);
            PurchasePrice.EDEX_PURCHASE_PRICE_ITEMS.ToList().ForEach(r => SavePurchasePriceItem(r, headerId));

            return headerId;
        }

        private Int64 SavePurchasePriceHeader(EDEX_PURCHASE_PRICE PurchasePrice)
        {  
            using (var connection = new OracleConnection(this.connectionString))
            {
                connection.Open();
                using (var command = new OracleCommand())
                {
                    command.Connection = connection;
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "ibsdbo.USP_ADD_EDEX_PURCH_PRICE_H";
                    command.Parameters.Clear();
                    command.Parameters.Add("p_ID_PRICE_HEADER", OracleType.Number).Direction = ParameterDirection.Output;
                    command.Parameters.AddWithValue("p_SUPIBSCODE", PurchasePrice.SUPIBSCODE);
                    command.Parameters.AddWithValue("P_ORDER_DATE", PurchasePrice.ORDER_DATE);
                    command.ExecuteNonQuery();
                    return Convert.ToInt64(command.Parameters["p_ID_PRICE_HEADER"].Value);
                }
            }
        }

        private void SavePurchasePriceItem(EDEX_PURCHASE_PRICE_ITEM PurchasePriceItem, Int64 headerId)
        {
            using (var connection = new OracleConnection(this.connectionString))
            {
                connection.Open();
                using (var command = new OracleCommand())
                {
                    command.Connection = connection;
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "ibsdbo.USP_ADD_EDEX_PURCH_PRICE_I";
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("p_ID_PRICE_HEADER", headerId);
                    command.Parameters.AddWithValue("p_ITEMCODE", PurchasePriceItem.ITEMCODE);
                    command.Parameters.AddWithValue("p_PURCHASE_PRICE", PurchasePriceItem.PURCHASE_PRICE);                    
                    command.ExecuteNonQuery();
                }
            }
        }       
    }
}
